package com.wl.dzt.init;

import com.wl.dzt.basic.ApplicationContext;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.core.dao.JDao;
import com.wl.dzt.sys.core.dao.curd.CrudCommand;
import com.wl.dzt.sys.core.dao.mate.TableHandler;
import com.wl.dzt.sys.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;


/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 数据库初始化工作
 */
@Order(1)
@Component
public class DataBaseConfigInit implements ApplicationRunner {
    protected static final Logger log = LoggerFactory.getLogger(DataBaseConfigInit.class);

    @Resource
    private DataSource dataSource;
    @Resource
    private JDao dao;

    @Override
    public void run(ApplicationArguments arguments) {
        TableHandler.init();
        initAppInof();
        initDataBaseType();
        staticRegs();
    }

    /**
     * 初始化应用信息
     */
    public void initAppInof() {
        try (Connection connection = dataSource.getConnection()) {
            ApplicationContext.DATABASE_VERSION = connection.getMetaData().getDatabaseProductVersion();
            ApplicationContext.SYSTEM_VERSION = System.getProperty("os.name");
            ApplicationContext.SYSTEM_IP = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化数据库类型
     * 支持mysql,oracle和sqlserver
     */
    private void initDataBaseType() {
        try {
            DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
            ApplicationContext.DATABASE_TYPE = metaData.getDatabaseProductName().toLowerCase();
            // 根据连接类型设置应该适配的数据库
            CrudCommand crudCommand = SpringUtil.getBean(ApplicationContext.DATABASE_TYPE);
            dao.setCommand(crudCommand);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 为DB注入spring中的DAO
     */
    private void staticRegs() {
        DB.J_DAO = SpringUtil.getBean(JDao.class);// 为DB注入DAO
    }

}
